<?php
/**
 * @author     Thibaut Cromphaut, Gaïtano Boeraeve, Matthias Mercy
 * @copyright  Copyright (c) 2011 memorygame
 */
class Application_Model_LevelMapper extends Ahs_Model_Mapper
{

    public function __construct(array $options = null)
    {
        parent::__construct($options);
        $this->DbTableName = 'Application_Model_DbTable_Levels';
    }

    /**
     * Level met een bepaald id ophalen
     * 
     * @param integer $id
     * @return Application_Model_Level
     */
    public function fetchById($id)
    {
        $row = $this->getDbTable()->fetchRow(array('level_id = ?' => $id));

        return $this->_toLevel($row);
    }

    /**
     * Level met een bepaald WorldId ophalen
     * 
     * @param integer $id
     * @return Application_Model_Level
     */
    public function fetchFirstByWorldId($id)
    {
        $row = $this->getDbTable()->fetchRow(array('worlds_world_id = ?' => $id));

        return $row["level_id"];
    }
    
    /**
     * Alle Levels ophalen
     * 
     * @return array
     */
    public function fetchAll()
    {        
        $sort = $this->getDbTable()->select()->order(array('level_numberofcards ASC', 'level_time DESC'));
        $rows = $this->getDbTable()->fetchAll($sort);

        return $this->_toLevels($rows);
    }
    
    /**
     * Alle levels met usergegevens ophalen
     * 
     * @return array
     */
    public function fetchAllForUser($worldId, $userId)
    {        
        
        $table = $this->getDbTable();

        $select = $table->select()->setIntegrityCheck(false);
        $select->from('levels')->joinLeft(array('userLevel' => 'user_has_levels'),'levels.level_id=userLevel.level_id')
                ->where('levels.worlds_world_id LIKE :worldId AND userLevel.user_id LIKE :userId')
                ->bind( array(':worldId' => $worldId, ':userId' => $userId) )                                
               ->order('levels.level_id ASC');
        /*if($limit !== false && $limit > 0)
        {
            $select->limit($limit);
        }*/
        $rows = $table->fetchAll($select);        

        return $this->_toLevels($rows);
    }
    
    /**
     * Alle Levels ophalen op basis van WorldId
     * 
     * @return array
     */
    public function fetchLevelsByWorldId($id)
    {           
        $table = $this->getDbTable();              
        $rows = $table->fetchAll(array('worlds_world_id = ?' => $id));

        return $this->_toLevels($rows);
    }

    /**
     * Geef het aantal levels per wereld terug
     * 
     * @return integer
     */
    public function getCount($worldId)
    {        
        $table = $this->getDbTable();
        $select = $table->select();
        $select->from($table, array('count(*) as count'))
                ->where('worlds_world_id LIKE :worldId')
                ->bind( array(':worldId' => $worldId) );
        
        $rows = $table->fetchAll($select);
        
        return $rows[0]->count;       
    }    
    
    /**
     * Geef het aantal levels terug
     * 
     * @return integer
     */
    public function getTotalCount()
    {        
        $table = $this->getDbTable();
        $select = $table->select();
        $select->from($table, array('count(*) as count'));
        
        $rows = $table->fetchAll($select);
        
        return $rows[0]->count;        
    } 
    
    /**
     * Level opslaan
     *
     * @param Application_Model_Level $level
     */
    public function save(Application_Model_Level $level)
    {
        $data = array(            
            'level_name'            =>$level->Name,           
            'level_time'            =>$level->Time,
            'level_numberofcards'   =>$level->NumberOfCards,
            'level_pictureUrl'      =>$level->PictureUrl,
            'worlds_world_id'       =>$level->WorldId,           
        );        

        if (null == $level->Id) {
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('level_id = ?' => $level->Id));
        }
    }
    
    /**
     * level verwijderen
     */
    public function delete($id)
    {   
        if (null != $id) {  
            $this->getDbTable()->delete(array('level_id = ?' => $id));
        } 
    }
    
    /**
     * @param Zend_Db_Table_Row_Abstract $row
     * @return Application_Model_Level 
     */
    private function _toLevel(Zend_Db_Table_Row_Abstract $row = null)
    {
        $level = new Application_Model_Level();
        $worldMapper = new Application_Model_WorldMapper();

        if ($row) {
            $level->Id              = $row['level_id'];
            $level->Name            = $row['level_name'];
            $level->Time            = $row['level_time'];
            $level->NumberOfCards   = $row['level_numberofcards'];
            $level->PictureUrl      = $row['level_pictureUrl'];
            $level->WorldId         = $row['worlds_world_id'];            
            $level->World           = $worldMapper->fetchById($row['worlds_world_id']);           
            
            if(isset($row['userHasLevel_score']))
                $level->UserScore   = $row['userHasLevel_score'];            
            if(isset($row['userHasLevel_time']))
                $level->UserTime    = $row['userHasLevel_time'];            
            if(isset($row['userHasLevel_tries']))
                $level->UserTries   = $row['userHasLevel_tries'];            
            if(isset($row['userHasLevel_unlocked']))
                $level->UserUnlocked   = $row['userHasLevel_unlocked'];   
        }

        return $level;
    }

    /**
     * @param Zend_Db_Table_Rowset_Abstract $rows
     * @return array
     */
    private function _toLevels(Zend_Db_Table_Rowset_Abstract $rows = null)
    {
        $levels = array();

        if ($rows) {
            foreach ($rows as $row) {
                $levels[] = $this->_toLevel($row);
            }
        }
        
        return $levels;
    }

}


